let net = require('net')

//广播b:内容 表示广播      私聊c:对方的用户名    列出用户列表l   修改昵称n:新名字

let clients = {}
let server = net.createServer(socket => {
    let key = socket.remoteAddress+socket.remotePort;
    socket.write('欢迎光临聊天室，你的地址是'+key+'\r\n')
    clients[key] = {
        nickname: '匿名',
        socket
    }
    socket.setEncoding('utf8')
    socket.on('data', data => {
        data = data.replace(/\r\n/, '')
        let type = data.slice(0,1);
        switch(type){
            case 'b':
                let text = data.slice(2)
                boardcast(text)
                break;
            case 'c':
                let values = data.split(':')
                let toUser = values[1];
                let toText = values[2];
                sendTo(toUser, toText)
                break;
            case 'l':
                list()
                break;
            case 'n':
                let newName = data.slice(2);
                let oldUserObj = clients[key]
                oldUserObj.nickname = newName
                socket.write('你的用户名修改为'+newName+'\r\n')
                break;
            default:
                socket.write('此命令不能识别')
                break;
        }
    })
    socket.on('end', function(){
        socket.destroy();
        delete clients[key]
    })
    // 列出所有用户
    function list(){
        let result = "在线用户列表：\r\n";
        for(let user in clients){
            result += clients[user].nickname+'\r\n'
        }
        socket.write(result)
    }

    function sendTo(toUser, text){
        let toUserObj;
        for(let user in clients){
            if(clients[user].nickname == toUser){
                toUserObj = clients[user]
                break;
            }
        }
        if(toUserObj){
            let nickname = clients[key].nickname
            toUserObj.socket.write(`${nickname}:${text}\r\n`)
        }else{
            socket.write(`用户名不正确或已下线`)
        }
    }
    function boardcast(text){
        let nickname = clients[key].nickname
        for(let user in clients){
            if(clients.hasOwnProperty(user) && user != key){
                clients[user].socket.write(`${nickname}:${text}`)
            }
        }
    }
})
server.listen(8080)